package hr.fer.zpr.nmbp.project3.dao;

import java.io.File;

import org.exist.xmldb.DatabaseInstanceManager;
import org.xmldb.api.DatabaseManager;
import org.xmldb.api.base.Collection;
import org.xmldb.api.base.Database;
import org.xmldb.api.base.XMLDBException;
import org.xmldb.api.modules.XMLResource;

public class DAOFactory {

	private static String URI = "xmldb:exist:///db";
	private static String username = "admin";
	private static String password = "";
	private static String configFile = "conf.xml";
	private static String createDbIfDoesntExist = "true"; 
	private static String resId = "ebolnica-res";
	private static Collection col;
	
	// Kreirane instance
	private static BolestDAO bolestDAO;
	private static BolnicaDAO bolnicaDAO;
	private static PacijentDAO pacijentDAO;
	private static LijecnikDAO lijecnikDAO;
	private static DijagnozaDAO dijagnozaDAO;
	private static KartonDAO kartonDAO;
	
	public static void init() throws Exception {
		final String driver = "org.exist.xmldb.DatabaseImpl";

		// initialize database driver
		@SuppressWarnings("rawtypes")
		Class cl = Class.forName(driver);
		Database database = (Database) cl.newInstance();
		database.setProperty("create-database", createDbIfDoesntExist);
		database.setProperty("configuration", configFile);
		DatabaseManager.registerDatabase(database);
		
		col = DatabaseManager.getCollection(URI, username, password);
		XMLResource res = (XMLResource) col.getResource(resId);
		if(res == null){
			// Init db
			res = (XMLResource) col.createResource(resId, "XMLResource");
			res.setContent(new File("ebolnica_init.xml"));
			col.storeResource(res);
		}
		
		System.out.println(res.getContent());
	}

	public static void close(){
		if(col == null) return;
		
		DatabaseInstanceManager manager;
		try {
			manager = (DatabaseInstanceManager) col.getService("DatabaseInstanceManager", "1.0");
			manager.shutdown();
		} catch (XMLDBException e) {
			// Ignore
		}
	}
    
	public static BolestDAO getBolestDAO() {
		if(bolestDAO == null){
			bolestDAO = new BolestDAO(col);
		}		
		return bolestDAO;
	}	

	public static BolnicaDAO getBolnicaDAO() {
		if(bolnicaDAO == null){
			bolnicaDAO = new BolnicaDAO(col);	
		}
		return bolnicaDAO;
	}	

	public static DijagnozaDAO getDijagnozaDAO() {
		if(dijagnozaDAO == null){
			dijagnozaDAO = new DijagnozaDAO(col);
		}
		return dijagnozaDAO;
	}	

	public static KartonDAO getKartonDAO()	{
		if(kartonDAO == null){
			kartonDAO = new KartonDAO(col);
		}
		return kartonDAO;
	}	

	public static LijecnikDAO getLijecnikDAO()	{
		if(lijecnikDAO == null){
			lijecnikDAO = new LijecnikDAO(col);
		}
		return lijecnikDAO;
	}	

	public static PacijentDAO getPacijentDAO()	{
		if(pacijentDAO == null){
			pacijentDAO = new PacijentDAO(col);
		}
		return pacijentDAO;
	}
}
